        $(function () {  
            $("#usergrid").datagrid({
            	title: "用户管理",
                url : basePath+"user/list",
                width: "100%",  
                height: "100%",  
                singleSelect : false, /*是否选中一行*/
                pagination : true,/*是否显示下面的分页菜单*/
                border:true,
                rowStyler: function() {
                	return 'height: 48px';
                },  

                //rownumbers:true,
                columns : [ [  
                			   {checkbox : true , field : 'ck',width : '50',align : 'center'},
                			   {field : 'id', title : 'ID',width : '160',align : 'center',hidden:'true'}, 
                               {field : 'username',title : '用户名',width : '8.3%',align : 'center'},
                               {field : 'userNo',title : '工号',width : '8.3%',align : 'center'},
                               {field : 'phone',title : '电话号码',width : '8.3%',align : 'center'},
                               {field : 'deptName',title : '所属部门',width : '8.3%',align : 'center'},
                               {field : 'email',title : '电子邮件',width : '8.3%',align : 'center'},
                               {field : 'parentUserName',title : '直属上级',width : '8.3%',align : 'center'},
                               {field : 'userRoleName',title : '角色',width : '8.3%',align : 'center'},
                               {field : 'birthDate',title : '出生年月',width : '8.3%',align : 'center'},
                               {field : 'timeOfEntry',title : '入职时间',width : '8.3%',align : 'center'},
                               {field : 'sex',title : '性别',width : '8.3%',align : 'center',formatter:function(value,row,index){
                            	   if(value==1){
                            		   return "男";
                            	   }else if(value==0){
                            		   return "女";
                            	   }
                               	}
                               },
                               {field : 'status',title : '状态',width : '8.3%',align : 'center',formatter:function(value,row,index){
                            	   if(value==1){
                            		   return "在职";
                            	   }else if(value==0){
                            		   return "<div style='color:red'>已注销</div>";
                            	   }
                               	}
                               }, 
                               {field : 'affiliatedCompany',title : '所属公司id',width : '100',align : 'center',hidden:'true'},
                               {field : 'affiliatedCompanyString',title : '所属公司',width : '100',align : 'center',hidden:'true'},
                               {field : 'parentId',title : '上级领导id',width : '100',align : 'center',hidden:'true'},
                               {field : 'op',title : '操作',width : '150',align : 'center',formatter:function(value,row,index){
                            	   if(row.status==0){
                            		   return "<a class='fonta' href='#' onclick=activateUser("+row.id+");>激活用户<a/>"
                            	   }else{
                            		   var btn = "";
                            		   if(isShow){
                            			   btn+="&nbsp;&nbsp;";
                                    	   btn += "<a class='fonta' href='#' onclick='addUpdateUser("+row.id+");'>修改<a/>";                             			   
                            		   }
                            		  
                            		   if(isShow2){
                            			   btn+="&nbsp;&nbsp;";
                            			   btn += "<a class='fonta' href='#' onclick=deleteUser("+row.id+");>注销<a/>"
                            		   }
                            		  
                            		   if(isShow3){
                            			   btn+="&nbsp;&nbsp;";
                            			   btn += "<a class='fonta' href='#' onclick=resetUserPwd("+row.id+");>密码重置<a/>"; 
                            		   } 
                        			   
                            		   return btn;
                            	   }

                            	   
                               	}
                               }
                			   
                               
                ]],
            	loadMsg : '数据加载中,请稍候......'
            }); 
  
            var p = $('#usergrid').datagrid('getPager');  
            $(p).pagination({  
                /*  
                    页数文本框前显示的汉字 修改每页默认条数   
                    搜索pageList在jquery.easyui.min.js中修改，  
                    分页区下拉分页数量集合和默认每页分页条数  
                    striped属性 交替行换色  
                */  
                beforePageText: '第',  
                afterPageText: '页    共 {pages} 页',  
                displayMsg: '当前显示 {from}-{to} 条记录,共 {total} 条记录'  
            });  
        });  
  
        //搜索  
        function doSearch() {  
        	//alert($("#username").val());
        	//return;
            $('#usergrid').datagrid('load', {  
                username: $('#username').val(),
                userNo : $("#userNo").val()
            });  
        }
        
        function doReset() {  
        	$('#queryForm')[0].reset();
        	doSearch();
        }
  
        //自定义操作列  
        function formatOper(val, row, index) {  
            var str = '<a id="clickmeid" href="javascript:void(0);" onclick="showmenu(this);">修改</a>';  
            return str;  
        }  
        ///////////////////////////////////////////////////////      user
        function addUpdateUser(userId){
        	var title = "修改用户";
        	if(userId==null||userId==''){
        		title = "新增用户";
        	}
            $('#addupdateUserDlg').dialog({
                title: title,
                width: 800,
                height: 600,
                closed: false,
                cache: false,
                href: basePath+'user/navigator?page=user/addUpdateUser&userId='+userId,
                onLoad:function(){
                	initAddUpdateUserData(userId);
                },
                onClose:function(){
                	 $('#usergrid').datagrid('reload', {  
                     });  
              	   //window.location.href=basePath+"navigator?page=user/list";
                 },
                modal: true
            });       	
        }
        
        function initAddUpdateUserData(userId){
        	$("#userId").val(userId);
        	//初始化COMBOTREE-部门
        	var deptcombotree = $("#deptComboTree");
        	deptcombotree.combotree({
        	         url: basePath+"dept/loadDeptComboTree",//初始combotree
        	         cascadeCheck:false, 
                     valueField: 'id',  
                     textField: 'text',  
                     editable: false ,
        	         prompt: '请选择...',
        	         onlyLeafCheck:true,
        	         onSelect:function(node) {
        	        	 $("#userDeptId").val(node.id); 
        	         },
        	         onLoadSuccess:function(){
        	        	 
        	         },
        	         onBeforeExpand: function (node) {
        	         }
        	     });
        	//初始化COMBOBOX-人员
		    $('#userParent').combobox({
		        valueField: 'id',
		        textField: 'text',
		        editable:false,
		        url: basePath+'tree/loadUserParent',
	            onLoadSuccess:function(){ //默认选中第一条数据
	            	var data= $('#userParent').combobox("getData");
	                if (data.length > 0) {
	                	if($("#userParentId").val()!=''){
	                		$('#userParent').combobox('setValue', $("#userParentId").val());
	                	}else{
	                		$('#userParent').combobox('select', data[0].id);
	                	}
	                 
	                }
	            }
		    });
        	//初始化COMBOBOX-公司
		    $('#AffiliatedCompany').combobox({
		        valueField: 'id',
		        textField: 'text',
		        editable:false,
		        url: basePath+'tree/loadAffiliatedCompany',
	            onLoadSuccess:function(){ 

	            	if($("#affiliatedCompanydate").val()!=''&&$("#affiliatedCompanydate").val()!=0){
                		$('#AffiliatedCompany').combobox('setValue', $("#affiliatedCompanydate").val());
                	}
	            }
		    });
        	//deptcombotree.combotree('setValues',3);  
            //
		    var sex = $("#sexvalue").val();
		    if(sex!=''){
		    	$("input[name='sex'][value="+sex+"]").attr("checked",true); 
		    }
		    var rows = $('#usergrid').datagrid('getSelections');
		    if(rows!=''){
			    $('#birthDate').datebox('setValue', rows[0].birthDate);
			    $('#timeOfEntry').datebox('setValue', rows[0].timeOfEntry);
		    }

		    $('#level').combobox({
		        valueField: 'id',
		        textField: 'text',
		        editable:false,
		        url: basePath+'tree/loadSelectTree?type=userLevel',
	            onLoadSuccess:function(){ 
		            	var data= $('#level').combobox("getData");
   		                if (data.length > 0) {
   		                	$('#level').combobox('select', data[0].id);
   		                }
   		                if($("#userLevel").val()!=''){
   		                	$('#level').combobox('select', $("#userLevel").val());
   		                }
	            }
		    });	
		    
		    $('#station').combobox({
		        valueField: 'id',
		        textField: 'text',
		        editable:false,
		        url: basePath+'tree/loadSelectTree?type=userStation',
	            onLoadSuccess:function(){ 
		            	var data= $('#station').combobox("getData");
   		                if (data.length > 0) {
   		                	$('#station').combobox('select', data[0].id);
   		                }
   		                if($("#userStation").val()!=''){
   		                	$('#station').combobox('select', $("#userStation").val());
   		                }
	            }
		    });		    
        }
        
        ////////////
        function submitAddUpdateUser(){
        	var userId = $("#userId").val();
        	//var parentId = $("#userParent").val();
        	var userNo = $("#userNO").val();
        	var userName = $("#userName").val();
        	var phone = $("#phone").val();
        	var email = $("#email").val();
        	var userParentId = $('#userParent').combobox("getValue");
        	var userDeptId = $("#userDeptId").val();
        	//var password = $("#password").val();
        	var sex=$("input[name='sex']:checked").val();
            var birthDate=$("#birthDate").val();
            var timeOfEntry=$("#timeOfEntry").val();
            var AffiliatedCompany=$("#AffiliatedCompany").combobox("getValue");
            var level = $("#level").combobox("getValue");
            var station = $("#station").combobox("getValue");
            var salary = $("#salary").val();
            //alert(timeOfEntry);
        	if(userNo==''||userName==''||userDeptId==''){
        		$.messager.alert('错误提示','请输必填信息','warning');
        		return;
        	}
        	
        	if(!checkName(userName)){
        		$.messager.alert('错误提示','姓名必须是中文、数字和英文','warning');
        		return;
        	}
        	if(!checkUserNo(userNo)){
        		$.messager.alert('错误提示','工号必须是数字和字母','warning');
        		return;
        	}
//        	if(!checkMobile(phone)){
//        		$.messager.alert('错误提示','联系电话格式不正确','warning');
//        		return;
//        	}
        	if(!checkEmail(email)){
        		$.messager.alert('错误提示','电子邮箱格式不正确','warning');
        		return;
        	}
            $.ajax({
                type:"post",
                url:basePath+"user/addUpdateUser",
                data:{
                	userId:userId,
                	userParentId:userParentId,
                	userNo : userNo,
                	userName : userName,
                	userDeptId :userDeptId,
                	phone:phone,
                	email:email,
                	sex:sex,
                	birthDate:birthDate,
                	timeOfEntry:timeOfEntry,
                	affiliatedCompany:AffiliatedCompany,
                	level : level,
                	station : station,
                	salary : salary
                },
                cache:false,
                dataType: "json", //this is important
                success:function(result) {
                	if(result.result=='success'){
                     	$.messager.show({
                     		title:'提示',
                     		msg:'操作成功',
                     		timeout:5000,
                     		showType:'slide'
                     	}); 
                    	$('#usergrid').datagrid('reload');//刷新
                    	$('#addupdateUserDlg').dialog("close");
                	}else{
                		$.messager.alert('错误提示',result.result,'warning');
                	}

                },
                error:function(result){
                	$.messager.alert('错误提示',"操作失败",'warning');
                }
            });
        } 
        
        function toUserAuth(){
        	var title = "用户权限设置";
        	var rows = $('#usergrid').datagrid('getSelections');
        	if(rows.length>1){
        		$('#usergrid').datagrid('clearSelections');
        	}
        	if(rows.length==1){
            	var row = $('#usergrid').datagrid('getSelected');
        		if(row.status==0){
        			$.messager.alert('警告','该用户已被注销!','info');
        			return;
        		}
            	//$('#roleFrame').attr('src',basePath+'user/navigator?page=user/role&userId='+row.id);
                $('#roleDlg').dialog({
                	top:20,
                    title: title,
                    width: 350,
                    height: 500,
                    closed: false,
                    cache: true,
                    href: basePath+'user/navigator?page=user/role&userId='+row.id,
                    onLoad:function(){
                    	loadRoleTree(row.id);
                    	//setUserRoles(row.id);
                    },
                    modal: true
                }); 
                
        	}else{
        		$.messager.alert('警告','请选择一个用户!','info');
        	}
         	
        }
        function loadRoleTree(userId){
        	$('#roleTree').tree({
        		url : basePath+"role/loadRoleTree",
        		animate : true,
        		checkbox : true,
        		cascadeCheck : true,
        		onlyLeafCheck : false,
        		lines : false,
        		dnd : true,
        		formatter : function (node) {
        			return node.roleName;
        		},
        		onClick:function(node){
        		},
                onSelect: function (node) {
                	/*
                    var cknodes = $('#roleTree').tree("getChecked");
                    for (var i = 0; i < cknodes.length; i++) {
                        if (cknodes[i].id != node.id) {
                            $('#roleTree').tree("uncheck", cknodes[i].target);
                        }
                    }
                    if (node.checked) {
                        $('#roleTree').tree('uncheck', node.target);

                    } else {
                        $('#roleTree').tree('check', node.target);

                    }
                    */
                },        		
        		onContextMenu:function(e,node){

        		},
        		onLoadSuccess:function(){
                	$('#roleTree').tree('expandAll'); 
                	/*
                    $('#roleTree').find('span.tree-checkbox').unbind().click(function () {
                        $('#roleTree').tree('select', $(this).parent());
                        return false;
                    });
                    */
                	setUserRoles(userId);
        		}
        	});
        }
        
        function setUserRoles(userId){
            $.ajax({  
            	type: 'get',
                url: basePath+"/role/setUserRolesTreeCb",  
                data: {  
                    userId: userId,  
                },  
                dataType: "json",
                success: function (data) {  
        			$.each(data,function(i,n){	
        				var node = $("#roleTree").tree("find", n.roleId);//重点方法  
                        $("#roleTree").tree("check", node.target); 
        			});                	
 
                }  
            });        	
        }
        
        ///////////////
		function submitUserAuth(){
			  var userId = $("#userId").val();
			  var rows = $('#usergrid').datagrid('getSelections');
			  if(userId==''){
				  userId=rows[0].id;
			  }
			  //getchecked
	        	
	            var checkeds = $('#roleTree').tree('getChecked', 'checked');
	            
	            if(checkeds.length==''){
	            	$.messager.alert('警告','请选择一个角色!','info');
	            	return;
	            }
	            var arr = [];
	            for (var i = 0; i < checkeds.length; i++) {
	            	arr.push(checkeds[i].id);
	            }
	            
//	            alert(arr.join(','));
//	            return;
			  //
			      $.ajax({
			          type:"post",
			          url:basePath+"user/authUser",
			          data:{
			          	userId:userId,
			          	roleIds:arr.join(',')
			          },
			          cache:false,
			          dataType: "json", //this is important
			          success:function(result) {
			        	  if(result.result=='success'){
			        		  $('#usergrid').datagrid('reload');//刷新
			        		  $('#usergrid').datagrid('clearSelections'); 
			        		  cancelDlg("roleDlg");
		                     	$.messager.show({
		                     		title:'提示',
		                     		msg:'配置角色成功',
		                     		timeout:5000,
		                     		showType:'slide'
		                     	}); 
			        	  }
			        	  
			          },
			          error:function(result){
			        	  $.messager.alert('警告','配置角色失败','info');
			          }
			      });
		}
		
        function deleteUser(id,userNo){
        	$.messager.confirm('提示框', '你确定要注销该用户吗?',function(r){
        		if(r){
                    $.ajax({
                        type:"post",
                        url:basePath+"user/deleteUser",
                        data:{
                        	userId:id
                        },
                        cache:false,
                        dataType: "json", //this is important
                        success:function(result) {
                        	$('#usergrid').datagrid('reload');//刷新
	                     	$.messager.show({
	                     		title:'提示',
	                     		msg:'注销成功',
	                     		timeout:5000,
	                     		showType:'slide'
	                     	});
                        }
                    });        			
        		}

        	});
        }
        //////////////////
        function resetUserPwd(id){
        	$.messager.confirm('提示框', '你确定要重置密码吗?',function(r){
        		if(r){
                    $.ajax({
                        type:"post",
                        url:basePath+"user/resetUserPwd",
                        data:{
                        	userId:id
                        },
                        cache:false,
                        dataType: "json", //this is important
                        success:function(result) {
                        	//$('#usergrid').datagrid('reload');//刷新
	                     	$.messager.show({
	                     		title:'提示',
	                     		msg:'密码修改成功',
	                     		timeout:3000,
	                     		showType:'slide'
	                     	});
                        }
                    });        			
        		}

        	});        	
        }
        ////////////////////
        function activateUser(id){
        	$.messager.confirm('提示框', '你确定要激活该用户吗?',function(r){
        		if(r){
                    $.ajax({
                        type:"post",
                        url:basePath+"user/activateUser",
                        data:{
                        	userId:id
                        },
                        cache:false,
                        dataType: "json", //this is important
                        success:function(result) {
                        	$('#usergrid').datagrid('reload');//刷新
	                     	$.messager.show({
	                     		title:'提示',
	                     		msg:'用户激活成功',
	                     		timeout:3000,
	                     		showType:'slide'
	                     	});
                        }
                    });        			
        		}

        	});        	
        }
        
        function deleteUsers(){
        	var rows = $('#usergrid').datagrid('getSelections');
        	if(rows.length == 0 ){
        		$.messager.alert('错误提示','请选择要删除的用户！','warning');
        		return;
        	}
        	var ids = [];
        	//var rows = $('#usergrid').datagrid('getSelections');
        	for(var i=0; i<rows.length; i++){
        		ids.push(rows[i].id);
        	}
        	//alert(ids.join(','));
        	$.messager.confirm('提示框', '你确定要删除用户吗?',function(r){
        		if(r){
        		    $.ajax({
        		        type:"post",
        		        url:basePath+"user/deleteUsers",
        		        data:{
        		        	ids:ids.join(',')
        		        },
        		        cache:false,
        		        dataType: "json", //this is important
        		        success:function(result) {
        			    	if(result.result=="success"){
        			    		$('#usergrid').datagrid('reload');//刷新
        		             	$.messager.show({
        		             		title:'提示',
        		             		msg:'删除成功',
        		             		timeout:3000,
        		             		showType:'slide'
        		             	});			    		
        			    		
        			    	}
        		        },
        		        error:function(){
        		        	$.messager.alert('错误提示','操作出错','warning');
        		        }
        		    });
        		    $('#usergrid').datagrid('clearSelections'); 
        		}
        	});         	
        }
        
        function cancelDlg(dlgName){
        	$('#usergrid').datagrid('clearSelections');
        	$('#'+dlgName).dialog("close");
        	 
        }